package com.demo.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.demo.entity.UserEntity;

public class FactoryUtil {
	private static SessionFactory sessionfactory = null;

	public static synchronized void createSessionFactory() {
		if (sessionfactory == null) {
			Configuration cfg = new Configuration();
			// cfg.configure();// 读取hibernate.cfg.xml
			// new Configuration();// 默认读取hibernate.properties
			// cfg.addPackage("com.demo.entity");
			cfg.addAnnotatedClass(UserEntity.class);
			// cfg.configure();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
			sessionfactory = cfg.buildSessionFactory(serviceRegistry);
		}
	}

	public static Session crateSeession() {
		if (sessionfactory == null) {
			createSessionFactory();
		}
		return sessionfactory.getCurrentSession();
	}

	public static void main(String[] args) {
		crateSeession();
	}
}
